#!/usr/bin/python
# -*- coding:UTF8 -*-

import os
import time

import requests
import json

singer_name = input("请输入歌手姓名：")
page = int(input('请输入需要下载几页：'))
if not os.path.exists(f'./测试数据/{singer_name}'):
    os.mkdir(f'./测试数据/{singer_name}')

url = f'https://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key={singer_name}&pn={page}&rn=30&httpsStatus=1&reqId=8b486260-c538-11ec-ad00-2576c65ffc89'
user_agent = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',
    'Cookie': 'Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1650960041; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1650960041; _ga=GA1.2.941168366.1650960041; _gid=GA1.2.273120037.1650960041; kw_token=6NKJWYBFA0A',
    'csrf': '6NKJWYBFA0A',
    'Host': 'www.kuwo.cn',
    'Referer': 'https://www.kuwo.cn/search/list?key=%E5%B0%8F%E9%98%BF%E4%B8%83',
    'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': "Windows",
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.'
}
# 1.拿到每一页歌曲名和歌曲编码
for page in range(1, page + 1):
    r = requests.get(url=url, headers=user_agent).text
    r = json.loads(r)
    lists = r['data']['list']
    # reqId = r['reqId']
    for dicts in lists:
        name = dicts['name']
        rid = dicts['rid']
        # print(dicts)
        # 2.拿到每个歌曲的下载地址
        # type类型换成 convert_url3 可以获取付费歌曲,酷我在 2021 年 9 月份更换过接口
        # https://www.kuwo.cn/api/v1/www/music/playUrl?mid={rid}&type=music&httpsStatus=1&reqId=18f09490-c578-11ec-a7f8-75172e8def70
        url = f'https://www.kuwo.cn/api/v1/www/music/playUrl?mid={rid}&type=convert_url3&httpsStatus=1&reqId=18f09490-c578-11ec-a7f8-75172e8def70'
        r = requests.get(url=url, headers=user_agent).text
        r = json.loads(r)
        # msg = r['msg']
        # if msg !='success':
        #     continue
        # else:
        url = r['data']['url']
        # print(r)
        r = requests.get(url=url).content
        path = f'./测试数据/{singer_name}/{name}.mp3'
        with open(path, 'wb') as file:
            file.write(r)
            print(f'{name} 下载完成！！！')
            time.sleep(2)
